<template>
	<view class="u-page">
		<div class="cards">
			<!-- 可滚动的客户列表 -->
                    <scroll-view scroll-y="true" style="flex: 1; margin-top: 10px;">
                        <view class="cards">
                            <view 
                                class="card" 
                                v-for="item in dtReport" 
                                :key="item.SSC_ORDER_LINES_LOTS_ID"
                                style="display: flex; align-items: center; border: 1px solid #eee; margin-bottom: 10px; padding: 10px; border-radius: 8px;"
                            > <u-checkbox-group>
                                <u-checkbox 
                                    :value="selectedKh.includes(item.SSC_ORDER_LINES_LOTS_ID)" 
                                    @change="toggleKh(item.SSC_ORDER_LINES_LOTS_ID)"
                                />
								</u-checkbox-group>
                                <view style="margin-left: 10px; flex: 1;">
                                    <div>订单明细：{{item.SSC_ORDER_LINES_LOTS_ID}}</div>
                                    <div>商品信息：{{item.GOODS_INFO}}</div>
									<div>生产厂家：{{item.PRODUCT_LOCATION}}</div>
                                    <div>批号：{{item.LOT_NO}}</div>
									<div>效期：{{formatDate(item.EXPIRE_DATE)}}</div>
                                    <div>出库数量：{{item.QTY}}</div>
									<div>登记数量：{{item.ACT_QTY}}</div>
                                </view>
                            </view>
                        </view>
                    </scroll-view>

                    <!-- 固定底部按钮 -->
                    <view class="btn">
                        <u-button type="primary" @click="handleGenerate">生成</u-button>
                    </view>
		</div>

		<!-- 悬浮搜索 -->
		<view class="fixed-search" @click="handleRightClick">
			<u-icon name="search" color="#fff" size="28"></u-icon>
		</view>
		<!-- 搜索弹窗 -->
		<u-popup :show="show" closeable @close="handleClose" @open="handleOpen" mode="right">
			
			<view class="popup-card">
				<u--form labelPosition="top" :model="model1" :rules="rules" ref="form1">
					<u-form-item label="客户ID" prop="userInfo.ClientId" borderBottom ref="ClientId"
						@click="showKh = true;hideKeyboard()">
						<u--input v-model="model1.userInfo.ClientId" placeholder="请点击选择..." disabled
							disabledColor="#ffffff" border="none"></u--input>
					</u-form-item>
					<u-form-item label="客户名称" prop="userInfo.ClientName" borderBottom ref="ClientId"
						@click="showKh = true;hideKeyboard()">
						<u--input v-model="model1.userInfo.ClientName" placeholder="请点击选择..." disabled
							disabledColor="#ffffff" border="none"></u--input>
					</u-form-item>
					<u-form-item label="商品信息" prop="userInfo.goodsCode" borderBottom ref="goodsCode">
						<u--input v-model="model1.userInfo.goodsCode" placeholder="请输入..." border="none"></u--input>
					</u-form-item>
                    <u-form-item label="销售代表" prop="userInfo.saleName" borderBottom ref="saleName">
						<u--input v-model="model1.userInfo.saleName" placeholder="请输入..." border="none"></u--input>
					</u-form-item>
					<u-form-item label="批号信息" prop="userInfo.ls_lotno" borderBottom ref="ls_lotno">
						<u--input v-model="model1.userInfo.ls_lotno" placeholder="请输入..." border="none"></u--input>
					</u-form-item>
					<u-form-item label="登记情况" prop="userInfo.ls_dj_flag" borderBottom ref="ls_dj_flag"
						@click="showDj = true; hideKeyboard()">
					<u--input 
						v-model="model1.userInfo.ls_dj_flag" 
						placeholder="请点击选择..." 
						readonly
						border="none">
					</u--input>
					</u-form-item>
					<u-form-item label="销售部门" prop="userInfo.SaleOrg_name" borderBottom ref="SaleOrg_name"
						@click="showDepartment = true; hideKeyboard()">
						<u--input v-model="model1.userInfo.SaleOrg_name" placeholder="请点击选择..." disabled
							disabledColor="#ffffff" border="none">
						</u--input>
					</u-form-item>
					<u-form-item label="政策录入开始" prop="userInfo.StartDate" borderBottom ref="item1"
						@click="showStartDate = true; hideKeyboard()">
						<u--input v-model="model1.userInfo.StartDate" placeholder="请点击选择..." disabled
							disabledColor="#ffffff" border="none">
						</u--input>
					</u-form-item>
					<u-form-item label="政策录入结束" prop="userInfo.EndDate" borderBottom ref="item1"
						@click="showDate = true; hideKeyboard()">
						<u--input v-model="model1.userInfo.EndDate" placeholder="请点击选择..." disabled
							disabledColor="#ffffff" border="none">
						</u--input>
					</u-form-item>
				</u--form>
			</view>
			<!-- 部门 -->
			<u-picker title="销售部门" :show="showDepartment" ref="uPicker" :columns="saleList" keyName="SALE_ORG_NAME"
				@close="handleCancelDepartment" @cancel="handleCancelDepartment" @change="changeHandler"
				@confirm="handleConfirmDepartment"></u-picker>
			<!-- 登记情况 -->
			    <u-picker 
			        title="登记情况" 
			        :show="showDj" 
			        ref="uPicker" 
			        :columns="djList" 
			        keyName="label"
			        @close="handleCancelDj" 
			        @cancel="handleCancelDj"
			        @confirm="handleConfirmDj"
			        @change="changeHandler2"
			    />
			<!-- 日期 -->
			<u-datetime-picker title="政策录入日期" :show="showStartDate" :value="Startdate" mode="date" closeOnClickOverlay
				@cancel="handleCancelDates" ref="datetimePicker" @close="handleCancelDates" @confirm="handleConfirms">
			</u-datetime-picker>
			<u-datetime-picker title="政策录入日期" :show="showDate" :value="date" mode="date" closeOnClickOverlay
				@cancel="handleCancelDate" ref="datetimePicker" @close="handleCancelDate" @confirm="handleConfirm">
			</u-datetime-picker>
			<u-popup :show="showKh" mode="center" :round="10" closeable @close="handleCloseKh">
				<view class="kh-card">
					<div class="search">
						<u-search placeholder="请输入..." :showAction="false" v-model="keyword" @search="handleSearchKh">
						</u-search>
					</div>
					<div class="cards">
						<div class="card" v-for="item in khList" :key="item.COM_PARTY_ID" @click="handleClickKh(item)">
							<div>客户ID：{{item.COM_PARTY_ID}}</div>
							<div>客户名称：{{item.PARTY_NAME}}</div>
							<div>客户代码：{{item.PARTY_OPCODE}}</div>
							<div>拼音：{{item.SPELL}}</div>
						</div>
					</div>
				</view>
			</u-popup>
			<!-- 底部固定按钮 -->
			<view class="btn-group">
			<u-button
				:plain="true"
				text="重置"
				size="small"
				:hairline="true"
				@click="handleReset"
			></u-button>
			<u-button type="primary" text="搜索" size="small" @click="handleSubmit"></u-button>
			</view>
		</u-popup>

	</view>
</template>

<script>
	import store from "@/store";
	import dayjs from "dayjs"
	import _ from "lodash"
	import {
		getSaleDepartment,
		searchKh,
		searchZhengming,
		updateDengji,
		generateZhengming
	} from "@/api";
	export default {
		filters: {
			filterTimes(val) {
				if (val) {
					return dayjs(val).format("YYYY-MM-DD")
				} else {
					return val
				}
			},
			filterOrgName(val) {
				if (val) {
					return val.substr(0, 3)
				} else {
					return ''
				}
			}
		},
		data() {
			return {
				subAmount: Number(0).toFixed(2),
				writeAmount: Number(0).toFixed(2),
				showModal: false,
				currentRow: {},  // 保存当前点击的数据
				title: "提示",
				content: "是否确认提交?",
				page: {
					current: 1,
					size: 10,
					total: 0
				},
				showStartDate: false,
				khList: [],
                selectedKh: [], // 保存选中的客户 ID
				keyword: "",
				showKh: false,
				showDepartment: false,
			    showDj: false,
				showDate: false,
				date: Number(new Date()),
				Startdate: Number(new Date()),
				status_height: 44,
				show: false,
				NowLotId: "",
				djList: [
				            [
				                { label: '已登记', value: 'TRUE' },
				                { label: '未登记', value: 'FALSE' }
				            ]
				    ],
				model1: {
					userInfo: {
                        saleName: "",
						SaleOrg: "",
						ClientId: "",
						ClientCode: "",
						StartDate: dayjs().startOf('month').format('YYYY-MM-DD'),
						EndDate: dayjs().format('YYYY-MM-DD'),
						goodsCode: "",
						purNo: "",
						px: "false",
						px_name: "记账日期",
						userid: "",
						pagesize: 1,
						pageindex: 10,
						ls_lotno:"",
						ls_dj_flag:"",
						ls_user_type:""

					},
				},
				formData: {
					ls_client_id: '',
					ls_client_name: '',
					goods_code: '',
					ls_sale_name: '',
					ls_sale_org: '',
					ls_lotno: '',
					ls_dj_flag: '',
					ls_create_start: '',
					ls_create_end: '',
					ls_user_type: '',
					ls_user_sets_id: '',
					ls_inv_owner:'',
				},
				shenCheng: {
					ls_client_id: '',
					ls_vender_id: '',
					ls_inv_owner:'',
					ls_user:'',
					ssc_order_lines_lots_id:''
				},

				dtReport: [], // 政策查询结果
				rules: {
					'userInfo.ClientId': {
						type: 'string',
						required: true,
						message: '请选择客户',
						trigger: ['blur', 'change']
					},
				},
				saleList: [
					[]
				],
				dtReport: [
					
				],
				dtReport1: [
					
				],
				gridview1: [],
				gridview2: []
			}
		},
		computed: {
			remainAmount() {
				return Number(this.subAmount - this.writeAmount).toFixed(2)
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form1.setRules(this.rules)
		},
		onLoad() {
			this.status_height = store.state.status_height
			// 请求销售部门和编码
			this.fetchSaleDepartment()
		},
		methods: {	
			formatDate(value) {
				if (!value) return ''
				// 例如 value: "2025-09-23T10:20:30"
				return value.split('T')[0]
			},
            toggleKh(id) {
                if (this.selectedKh.includes(id)) {
                this.selectedKh = this.selectedKh.filter(i => i !== id)
                } else {
                this.selectedKh.push(id)
                }	
            },
            // 生成
			async handleGenerate() {
				//console.log("选中的客户ID：", this.selectedKh)               
				if (this.selectedKh.length === 0) {
				        uni.showToast({ 
				            title: '请先选择要生成的记录', 
				            icon: 'none',
				            duration: 2000
				        })
				        return
				}
				
				if (this.selectedKh.length > 0) {
					// 打开遮罩层
					uni.showLoading({
					title: '正在生成...',
					mask: true
					})

					try {
						this.shenCheng.ssc_order_lines_lots_id = this.selectedKh.join(',')
						this.shenCheng.ls_user = uni.getStorageSync('userinfo').SALER
						this.shenCheng.ls_client_id = this.model1.userInfo.ClientId
						this.shenCheng.ls_inv_owner = uni.getStorageSync('userinfo').COM_PARTY_ID

						console.log('shenCheng', this.shenCheng)
						const res = await generateZhengming(this.shenCheng)
						console.log('res', res)
 
                       // 先隐藏loading
                       uni.hideLoading()
					
					   // if (res.State === 1) {
						  //   uni.showToast({ title: '生成成功', icon: 'success' })
						  //   setTimeout(() => {
							 //    this.handleSubmit() // 重新查询
							 //    this.selectedKh = [] // 清空选中
							 //    this.dtReport.splice(0)
						  //   }, 1000) 						
					   //  } 
					   if (res.State === 1) {
					               // 使用 showModal 代替 showToast，显示完整消息
					               uni.showModal({
					                   title: '温馨提示',
					                   content: res.Msg,
					                   showCancel: false,
					                   confirmText: '确认',
					                   success: (modalRes) => {
					                       if (modalRes.confirm) {
					                           // 用户点击确认后执行刷新
					                           //console.log('用户点击确认，开始刷新界面')
					                           this.handleSubmit() // 重新查询
					                           this.selectedKh = [] // 清空选中
					                       }
					                   }
					               })
					           } 
						else {
						    uni.showToast({ title: res.Msg || '生成失败', icon: 'none' })
					    }
					    } catch (e) {
					        uni.showToast({ title: '网络错误', icon: 'none' })
					    } finally {
					        uni.hideLoading() // 关闭遮罩
					    }
				}
			},
			// formatDate(date) {
			// 	if (!date) return '';
			// 	return date.split('T')[0];
			// },	
			// 重置
			handleReset(){
				this.model1.userInfo = {
					saleName: "",
					SaleOrg: "",
					ClientId: "",
					ClientCode: "",
					StartDate: dayjs().startOf('month').format('YYYY-MM-DD'),
					EndDate: dayjs().format('YYYY-MM-DD'),
					goodsCode: "",
					purNo: "",
					px: "false",
					px_name: "记账日期",
					userid: "",
					pagesize: 1,
					pageindex: 10,
					ls_lotno:"",
					ls_dj_flag:"",
					ls_user_type:""
				}
			},
			handleConfirmDepartment(val) {
				const row = val.value[0]
				this.model1.userInfo.SaleOrg_name = row.SALE_ORG_NAME
				this.model1.userInfo.SaleOrg = row.SALE_ORG
				this.model1.userInfo.SHORT_CODE = row.POSTCODE
				this.handleCancelDepartment()
			},
			handleCancelDates() {
				this.showStartDate = false
			},
			handleCancelDates() {
				this.showStartDate = false
			},
			handleConfirmDj(val) {
				const row = val.value[0]
				this.model1.userInfo.ls_dj_flag = row.label
				this.handleCancelDj()
			},
			handleCancelDj() {
			    this.showDj = false
			},
			handleCancelDates() {
				this.showStartDate = false
			},
			handleConfirms(e) {
				this.showStartDate = false
				this.model1.userInfo.StartDate = dayjs(e.value).format('YYYY-MM-DD')
			},
			handleConfirm(e) {
				this.showDate = false
				this.model1.userInfo.EndDate = dayjs(e.value).format('YYYY-MM-DD')
			},
			handleClickKh(row) {
				this.showKh = false
				this.model1.userInfo.ClientCode = row.PARTY_OPCODE
				this.model1.userInfo.ClientId = row.COM_PARTY_ID
				this.model1.userInfo.ClientName = row.PARTY_NAME
			},
			// 搜索客户
			async handleSearchKh(val) {
				if (!_.trim(val)) {
					return uni.showToast({
						title: "请输入搜索关键词"
					})
				}
				uni.showLoading({
					title: "搜索中",
					mask: true
				})
				try {
					const userinfo = uni.getStorageSync('userinfo')
					const res = await searchKh(val, userinfo.USER_ID)
					if (res.State == 1) {
						this.khList = res.Data
					} else {
						uni.showToast({
							title: res.Msg,
							icon: "error"
						})
					}
				} catch (e) {
					//TODO handle the exception
				} finally {
					uni.hideLoading()
				}
			},

			// 提交
			async handleSubmit() {
				// 先进行客户ID验证，不通过loading
				//console.log('点击搜索按钮，开始执行handleSubmit');
				if (!this.model1.userInfo.ClientId || this.model1.userInfo.ClientName.trim() === '') {
				        uni.showToast({ 
				            title: '请选择客户', 
				            icon: 'none',
				            duration: 2000
				        });
				        return;
				    }
				//console.log('客户ID验证通过，开始查询');	
				// 打开遮罩层
				uni.showLoading({
					title: '正在查询...',
					mask: true
				})

				try {
						this.formData.ls_client_id = this.model1.userInfo.ClientId
						this.formData.ls_client_name = this.model1.userInfo.ClientName
						this.formData.goods_code = this.model1.userInfo.goodsCode||''
						this.formData.ls_sale_name = this.model1.userInfo.saleName||''
						this.formData.ls_sale_org = this.model1.userInfo.SaleOrg||''
						this.formData.ls_lotno = this.model1.userInfo.ls_lotno||''
						this.formData.ls_dj_flag = this.model1.userInfo.ls_dj_flag||''
						this.formData.ls_create_start = this.model1.userInfo.StartDate||''
						this.formData.ls_create_end = this.model1.userInfo.EndDate||''
						this.formData.ls_user_type = uni.getStorageSync('userinfo').USER_TYPE||''
						this.formData.ls_user_name= uni.getStorageSync('userinfo').USER_NAME||''
						this.formData.ls_inv_owner = uni.getStorageSync('userinfo').COM_PARTY_ID||''
						this.formData.ls_user_sets_id= uni.getStorageSync('userinfo').SETS_ID||''

						console.log('model1', this.formData)
						const res = await searchZhengming(this.formData)

						if (res.State === 1) {
						this.dtReport = res.Data
						this.show = false
					} else {
					uni.showToast({ title: res.Msg || '查询失败', icon: 'none' })
					}
				} catch (e) {
					uni.showToast({ title: '网络错误', icon: 'none' })
				} finally {
					uni.hideLoading() // 关闭遮罩
				}
			},
			handleCancelPx() {
				this.showModal = false
			},
			handleClickDt(row){
				this.currentRow = row  // 保存当前点击的数据
			  	this.showModal = true  // 打开弹窗
				console.log('row',row)
				this.NowLotId=row.SSC_ORDER_LINES_LOTS_ID
			},
			handleCloseKh() {
				this.showKh = false
			},
			changeHandler(e) {
				const {
					columnIndex,
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				const row = this.saleList[columnIndex][index]
				this.model1.userInfo.SaleOrg_name = row.SALE_ORG_NAME
				this.model1.userInfo.SaleOrg = row.SALE_ORG
				this.model1.userInfo.SHORT_CODE = row.POSTCODE
			},
			async fetchSaleDepartment() {
				const userinfo = uni.getStorageSync('userinfo')
				const res = await getSaleDepartment(userinfo.COM_PARTY_ID)
				if (res.State == 1) {
					const {
						Data
					} = res
					this.saleList[0] = Data
				}
			},
			handleCancelDepartment() {
				this.showDepartment = false
			},
			handleCancelDate() {
				this.showDate = false
			},
			handleClose() {
				this.show = false
			},
			handleOpen() {

			},
			handleRightClick() {
				this.show = true
			},
			hideKeyboard() {
				uni.hideKeyboard()
			}
		}
	}
</script>

<style lang="scss">
	/* #ifndef APP-NVUE */
	page {
		background-color: $u-bg-color;
	}
	.popup-card {
		padding: 50rpx 32rpx;
		width: calc(100vw - 64rpx);
		height: calc(100vh - 100rpx);
		overflow-y: scroll;
	}

	.kh-card {
		padding: 20rpx 32rpx;
		width: calc(100vw - 64rpx);
		height: calc(100vh - 100rpx);
		overflow-y: scroll;

		.search {
			margin-top: 80rpx;
			margin-bottom: 50rpx;
		}

		.cards {
			.card {
				box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, .1);
				padding: 24rpx;
				border-radius: 8rpx;
				margin-bottom: 32rpx;

				div {
					font-size: 28rpx;
					line-height: 48rpx;
					color: #333333;
				}
			}
		}
	}

	.btn-group {
		position: sticky;
		bottom: 0;
		display: flex;
		justify-content: space-around;
		padding: 10px;
		background-color: #fff;
		z-index: 10;
	}
    .btn {
        position: fixed;
        bottom: 20rpx;
        left: 50%;
        transform: translateX(-50%);
        width: calc(100% - 64rpx);
        padding: 0 32rpx;
        z-index: 10;
    }

	.fixed-search {
		width: 80rpx;
		height: 80rpx;
		position: fixed;
		right: 8rpx;
		top: 50%;
		background-color: $u-primary;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 8rpx;
	}

	/deep/.u-form-item__body__left {
		width: 200rpx !important;
	}

	/deep/.u-form-item__body__left__content__label {
		font-size: 28rpx !important;
	}

	.panel {
		.content {
			display: grid;
			width: 100%;
			grid-template-columns: repeat(3, 1fr);
			grid-gap: 12rpx;

			.col {
				width: 100%;
				margin-bottom: 10rpx;
				display: flex;
				flex-direction: column;
				font-size: 24rpx;

				span {
					&:nth-child(2) {
						word-break: break-all;
						overflow: hidden;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
					}
				}
			}
		}
	}

	.u-input__content__field-wrapper input {
		font-size: 24rpx !important;
	}

	.col .u-input {
		padding: 0 !important;
		width: 160rpx !important;
	}

	.tool-page {
		padding: 0 36rpx;
		.remark {
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;

			span {
				font-size: 28rpx;
			}

			/deep/.u-input {
				display: inline !important;
				background-color: #fff !important;
				max-width: 600rpx !important;
				padding: 6rpx 9rpx !important;
			}
		}

		.page {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;

			span {
				font-size: 28rpx;
			}

			/deep/.u-input {
				display: inline !important;
				background-color: #fff !important;
				max-width: 100rpx !important;
				padding: 6rpx 9rpx !important;
			}

			.search-btn {
				margin-left: 10rpx;
				font-size: 28rpx;
				background-color: $u-primary;
				padding: 12rpx 18rpx !important;
				color: #fff;
				border-radius: 8rpx;
				cursor: pointer;
			}
		}

		.remark {}
	}

	.search-price {
		position: fixed;
		width: 100%;
		padding-top: 30rpx;
		background-color: #fff;
		z-index: 50;
		top: 62rpx;
		ul {
			padding: 0 32rpx;
			li {
				display: flex;
				align-items: center;
				margin: 20rpx 0;

				span {
					font-size: 24rpx;
					margin-right: 20rpx;
				}

				/deep/.u-input {
					background-color: #eeeeef !important;
				}

			}
		}
	}

	.fixed-search {
		/deep/.u-icon__icon {
			font-size: 56rpx !important;
		}
	}

.cards {
			.card {
				box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, .1);
				padding: 24rpx;
				border-radius: 8rpx;
				margin-bottom: 32rpx;

				div {
					font-size: 28rpx;
					line-height: 48rpx;
					color: #333333;
				}
			}
		}
.popup-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}


.popup-body {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx;
  padding-bottom: 120rpx; /* 预留按钮高度 */
}


.popup-footer {
  position: sticky;  /* 相对于容器底部固定 */
  bottom: 0;
  left: 0;
  width: 100%;
  background: #fff;
  border-top: 1px solid #eee;
  z-index: 10;
}

.confirm-btn {
  width: 100%;
  background-color: #2979ff;
  color: #fff;
  border-radius: 8rpx;
  height: 88rpx;
}



.drawer {
  position: relative;
  width: 100vw;
  height: 100vh;              /* 关键：让内部高度可算 */
  background: #fff;
}


.drawer-body {
  height: calc(100vh - 120rpx - env(safe-area-inset-bottom));
  height: calc(100vh - 120rpx - constant(safe-area-inset-bottom)); 
  overflow: auto;
  -webkit-overflow-scrolling: touch;
  padding: 20rpx;
}

.drawer-footer {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  border-top: 1px solid #eee;
  padding: 16rpx 20rpx calc(16rpx + env(safe-area-inset-bottom));
  padding-bottom: calc(16rpx + constant(safe-area-inset-bottom));   
  z-index: 10;
}

.detail-item {
  padding: 16rpx 0;
  border-bottom: 1px solid #eee;
//   display: flex;
  justify-content: space-between;
}
.label { font-size: 28rpx; color: #666; }
.value { 
	font-size: 31rpx; color: #333; 
	// text-align: right; 
}

/* 按钮 */
.confirm-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #2979ff;
  color: #fff;
  border-radius: 12rpx;
}


</style>
